package com.ruoyi.web.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.StatisticsVo;
import com.ruoyi.system.domain.vo.SysUserCompanyReqVo;
import com.ruoyi.system.domain.vo.SysUserReqVo;
import com.ruoyi.system.domain.vo.SysUserVo;
import com.ruoyi.system.service.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/api/user")
public class ApiUserController extends BaseController {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysLogininforService sysLogininforService;
    @Autowired
    private IChatRequireService chatRequireService;
    @Autowired
    private IChatRequirePlanService chatRequirePlanService;
    @Autowired
    private IChatRequireSummaryService chatRequireSummaryService;
    @Autowired
    private IAiUserFeedbackService userFeedbackService;

    @GetMapping("/mine")
    @ApiOperation(value = "查询当前用户信息")
    public AjaxResult mine() {
        // 查询当前用户基本信息
        SysUser sysUser = sysUserService.selectUserById(SecurityUtils.getUserId());
        if (null == sysUser) return AjaxResult.error("用户不存在");
        SysUserVo resp = new SysUserVo();
        BeanUtil.copyProperties(sysUser, resp);
        resp.setOpenId(sysUser.getUserName());
        resp.setUserName(sysUser.getNickName());
        resp.setCompanyMarginFlag("1"); // 默认已缴纳保证金
        resp.setCompanyAuthFlag(sysUser.getCompanyAuthFlag());
        resp.setCompanyName(sysUser.getCompanyName());
        resp.setCompanyLeader(sysUser.getCompanyCode());
        resp.setCompanyCode(sysUser.getCompanyCode());
        return AjaxResult.success(resp);
    }

    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    @ApiOperation(value = "修改当前用户信息（如用户昵称，头像等）")
    public AjaxResult update(@RequestBody SysUserReqVo req) {
        SysUser user = new SysUser();
        user.setUserId(SecurityUtils.getUserId());
        user.setAvatar(req.getAvatar());
        user.setNickName(req.getNickName());
        user.setSex(req.getSex());
        user.setUpdateBy(getUsername());
        return toAjax(sysUserService.updateUser(user));
    }

    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/update/company")
    @ApiOperation(value = "修改当前用户企业信息（如企业名称，企业编码，企业法人等）")
    public AjaxResult updateCompany(@RequestBody SysUserCompanyReqVo req) {
        SysUser user = new SysUser();
        user.setUserId(SecurityUtils.getUserId());
        // 默认认证通过
        user.setCompanyAuthFlag(StrUtil.isBlank(req.getCompanyAuthFlag()) ? "2" : req.getCompanyAuthFlag());
        user.setCompanyName(req.getCompanyName());
        user.setCompanyLeader(req.getCompanyLeader());
        user.setCompanyCode(req.getCompanyCode());
        user.setUpdateBy(getUsername());
        return toAjax(sysUserService.updateUser(user));
    }


    @Log(title = "用户意见反馈信息", businessType = BusinessType.INSERT)
    @PostMapping("/feedback")
    @ApiOperation(value = "新增用户意见反馈信息")
    public AjaxResult feedback(@RequestBody AiUserFeedback feedback) {
        // 保存用户反馈意见
        feedback.setUserId(getUserId());
        return toAjax(userFeedbackService.insertAiUserFeedback(feedback));
    }

    @GetMapping("/statistics")
    @ApiOperation(value = "用户相关数据统计信息")
    public AjaxResult statistics(@RequestParam(value = "days", required = false) Integer days) {
        // days天内的数据，没传该参数，则统计系统总数
        Map<String, Object> params = null;
        if (null != days && days > 0) {
            LocalDate today = LocalDate.now();
            LocalDate startDate = today.minusDays(days - 1); // 开始日期为今天之前的天数
            LocalDate endDate = today.plusDays(1); // 结束日期为今天之后的一天

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String beginTime = startDate.format(formatter);
            String endTime = endDate.format(formatter);

            params = new HashMap<>();
            params.put("beginTime", beginTime);
            params.put("endTime", endTime);
        }

        StatisticsVo statistics = new StatisticsVo();
        ChatRequire chatRequire = new ChatRequire();
        chatRequire.setParams(params);
        List<ChatRequire> requires = chatRequireService.selectChatRequireList(chatRequire);
        statistics.setChatRequireData(requires.isEmpty() ? "0" : String.valueOf(requires.size()));
        ChatRequirePlan chatRequirePlan = new ChatRequirePlan();
        chatRequirePlan.setParams(params);
        List<ChatRequirePlan> plans = chatRequirePlanService.selectChatRequirePlanList(chatRequirePlan);
        statistics.setChatRequirePlanData(plans.isEmpty() ? "0" : String.valueOf(plans.size()));
        ChatRequireSummary chatRequireSummary = new ChatRequireSummary();
        chatRequireSummary.setParams(params);
        List<ChatRequireSummary> summaries = chatRequireSummaryService.selectChatRequireSummaryList(chatRequireSummary);
        statistics.setChatRequireSummaryData(summaries.isEmpty() ? "0" : String.valueOf(summaries.size()));
        SysLogininfor loginLog = new SysLogininfor();
        loginLog.setParams(params);
        List<SysLogininfor> sysLogList = sysLogininforService.selectLogininforList(loginLog);
        statistics.setUserLoginData(sysLogList.isEmpty() ? "0" : String.valueOf(sysLogList.size()));
        return AjaxResult.success(statistics);
    }
}
